package cs236369.hw5;

import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;

import msg.*;

import common.dal.Transaction;
import common.logger.*;
import common.logger.Logger.LogLevel;

/**
 * Finds messages by location.<br>
 * To be used by a Web Service
 * 
 * @author Gal Lalouche
 */
public class SearchWSImpl implements SearchWS {
	
	/**
	 * The name of the application
	 */
	public static final String	APP_NAME	= "036933489AND037023231";
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see cs236369.hw5.SearchWS#searchLocal(double, double, double)
	 */
	@Override
	public String[] searchLocal(double locationX, double locationY, double d) {
		try (Transaction t = new Transaction()) {
			MessageManager $ = MessageManager.getNewInstance(t);
			Collection<Message> messages = $.getAllMessagesInRadius(new Location(locationY, locationX), d, null);
			messages.addAll($.getAllEventsInRadius(new Location(locationY, locationX), d, null, true));
			Collection<String> strings = new LinkedList<>();
			for (Message msg: messages) {
				String formatted = MessageFormat.format("{0}||{1}||{2}", msg.getLocation().getLongitude(), msg
						.getLocation().getLatitude(), msg.getContent());
				strings.add(formatted);
			}
			String[] result = new String[strings.size()];
			t.commit();
			return strings.toArray(result);
		} catch (SQLException e) {
			e.printStackTrace();
			CompositeLogger.getInstance().log(LogLevel.ERROR, e.getMessage());
			return new String[0];
		}
	}
	
	// empty result
	/*
	 * (non-Javadoc)
	 * 
	 * @see cs236369.hw5.SearchWS#searchKeywords(java.lang.String[])
	 */
	@Override
	public String[] searchKeywords(String[] args) {
		return new String[0];
	}
}
